
//网络请求
import { 
  getThemeData, 
  getMustRubData, 
  getWomenWearData,
  getWomenShoesData,
  getWomenShoesHotsData,
  getMaleShoesData,
  getMaleShoesHotsData,
  getUnderwearData,
  getUnderwearHotsData,
  gethomedecorationData,
  gethomedecorationHotsData,
  getkidwearData,
  getkidwearHotsData,
  getGuessYouLike
 } from './network/index.js';
$(function() {
  //首页渲染
  class Index {
    constructor() {
      this.init();
    }
    //初始化
    init() {
      //初始化dom
      this.initDom();
      //渲染头部菜单列表
      this.loadHeadListData();
      //渲染每日必抢模块
      this.loadMustRubData();
      //倒计时定时器
      this.countDownTimer = null;
      //倒计时功能
      this.countDown();
      //渲染女装模块
      this.loadWomenWearData();
      //渲染女鞋包包模块
      this.loadWomenShoesData();
      this.loadWomenShoesHotsData();
      //渲染男装男鞋模块
      this.loadMaleShoesData();
      this.loadMaleShoesHotsData();
      //渲染内衣模块
      this.loadUnderwearData();
      this.loadUnderwearHotsData();
      //渲染家纺家饰
      this.loadHomeDecorationData();
      this.loadHomeDecorationHotsData();
      //渲染母婴童装
      this.loadKidwearData();
      this.loadKidwearHotsData();
      //初始化单行多列轮播图
      this.initSildesSwiper();
      //初始化多行多列轮播图
      this.initCSlidesSwiper();
      //渲染猜你喜欢
      this.loadGuessYouLikeData();
      //背景变化的颜色数组
      // this.bgColorList = ['#CCEAE2', '#FF7D9C'];
      //获取头部菜单列表
      this.markets = $('.theme-market ul.markets');
      this.initBannerSwiper();
      //绑定事件
      this.bindEvent();
    }
    //绑定事件
    bindEvent() {
      //市场列表事件委托给每一个span小项
      this.markets.on('click', 'span', function() {
        let index = $(this).parent().attr('data-count');
        //计录当前的菜单项索引
        sessionStorage.setItem('menusActiveIndex', index);
        //每次跳转到列表页都要重置一下筛选方法和价额区间和显示筛选项的索引
        sessionStorage.setItem('sortActiveIndex', 0);
        sessionStorage.removeItem('page');
        sessionStorage.removeItem('sortKey');
        sessionStorage.removeItem('priceStage');
        window.open(`./goodsList.html#cateid=${$(this).attr('data-cateid')}`);
      });

      //跳转到详情页
      this.guessyoulike.on('click', 'li', function() {
        let goodsId = $(this).attr('data-tradeItemId');
        if(goodsId) {
          window.open(`./goodsDetail.html#id=${goodsId}`);
        }
      });
    }
    //初始化dom
    initDom() {
      this.headlist = $('.header-nav ul.markets');
      this.mustrubswiper = $('.must-rub #my-swiper-box .swiper-wrapper');
      //倒计时
      this.rubcounter = $('.must-rub .counter');
      this.rubhours = $('.must-rub .counter .hours');
      this.rubminutes = $('.must-rub .counter .minutes');
      this.rubseconds = $('.must-rub .counter .seconds');
      //女装容器
      this.womenwearswiper = $('.womenwear #my-swiper-box-womenwear .swiper-wrapper');
      //女鞋包包
      this.womenshoesswiper = $('.womenshoes .womenshoesswiper .swiper-wrapper');
      this.womenshoeshots = $('.womenshoes .recommend .rlist');

      //男装男鞋
      this.maleshoesswiper = $('.maleshoes .maleshoesswiper .swiper-wrapper');
      this.maleshoeshots = $('.maleshoes .recommend .rlist');

      //内衣
      this.underwearswiper = $('.underwear .underwearswiper .swiper-wrapper');
      this.underwearhots = $('.underwear .recommend .rlist');
      //内衣模块左侧图片
      this.underwearleftimg = $('.underwear .left-img');
      this.underwearimgTimer = null;
      this.toggleImg();

      //家纺家饰
      this.homedecorationswiper = $('.homedecoration .homedecorationswiper .swiper-wrapper');
      this.homedecorationhots = $('.homedecoration .recommend .rlist');

      //母婴童装
      this.kidwearswiper = $('.kidwear .kidwearswiper .swiper-wrapper');
      this.kidwearhots = $('.kidwear .recommend .rlist');

      //猜你喜欢
      this.guessyoulike = $('.guess-you-like .guess-you-like-list');

      //banner
      // this.banner = $('.banner_wrapper');
    }


    //单行多列轮播图初始化，每8秒更换
    initSildesSwiper() {
      Promise.all([this.loadMustRubData(), this.loadWomenWearData()])
      .then(() => {
        new Swiper('.my-swiper', {
          slidesPerView: 4,
          slidesPerGroup: 4,
          loop: true,
          autoplay: {
            disableOnInteraction: false,
            delay: 8000
          },
          observer: true,
          observeParents: true,
          navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
          }
        });
      })
    }

    // 多行多列轮播图初始化，每6秒更换
    initCSlidesSwiper() {
      Promise.all([this.loadKidwearData(), this.loadHomeDecorationData(), this.loadUnderwearData(), this.loadMaleShoesData(), this.loadWomenShoesData()])
      .then(() => {
        new Swiper('.my-common-swiper', {
          loop: true,
          observer: true,
          observeParents: true,
          autoplay: {
            disableOnInteraction: false,
            delay: 6000
          },
          pagination: {
            el: '.swiper-pagination',
            clickable: true
          }
        });
      })
    }

    //banner轮播图初始化,每6秒更换
    initBannerSwiper() {
      new Swiper('.banner-swiper', {
        autoplay: {
          disableOnInteraction: false,
          delay: 6000
        },
        loop: true,
        pagination: {
          el: '.swiper-pagination',
          clickable: true
        }
      });
      // let count = 0;
      // setInterval(() => {
      //   count++;
      //   this.changeBannerBgColor(this.bgColorList[count % this.bgColorList.length]);
      // }, 7000);
    }

    //实现轮播时背景变化,每过6秒更换一次
    changeBannerBgColor(bg) {
      this.banner.css({
        backgroundColor: bg
      });
    }
    //处理市场列表每一个类目的id
    handleHeadListItemId(str) {
      let reg = /(?<=\/)\d+(?=\?)/g;
      return str.match(reg)[0];
    }

    //获取头部导航主题市场商品数据列表
    loadHeadListData() {
      getThemeData((res) => {
        this.renderHeadList(res);
        this.savaGoodsListMenu();
      });
    }
    //渲染头部导航主题市场商品数据列表
    renderHeadList(res) {
      let str = ``;
      let count = 0;
      $.each(res.data, (i, item) => {
        str += `<li data-count='${count++}'>`;
        $.each(item.list, (i, value) => {
          let cateid = this.handleHeadListItemId(value.link);
          if(i === 0) {
            str += `<span data-cateid="${cateid}" class="cate">${value.title}</span>`;
          }else {
            if(i > 3) {
              str += '';
            }else {
              str += `<span data-cateid="${cateid}" ${value.is_red ? 'class="hot"' : ''} ${value.is_HotTag ? 'class="hotted"' : ''}>${value.title}</span>`;
            }
          }
        });
        str += `</li>`;
      });
      
      this.headlist.html(str);
    }

    //将类目id本地存储，携带到列表页
    savaGoodsListMenu() {
      let menus = [];
      let spanCate = $('.theme-market .markets li span.cate');
      $.each(spanCate, (index, ele) => {
        menus.push($(ele).attr('data-cateid'));
      });
      localStorage.setItem('menus', JSON.stringify(menus));
    }

    //获取每日必抢数据列表
    async loadMustRubData() {
      let res = await getMustRubData();
      this.renderMySwiper(this.mustrubswiper, res);
    }
    //获取女装专区数据列表
    async loadWomenWearData() {
      let res = await getWomenWearData();
      this.renderMySwiper(this.womenwearswiper, res);
    }

    //获取女鞋包包专区数据列表
    async loadWomenShoesData() {
      let res = await getWomenShoesData();
      this.renderMySwiperSix(this.womenshoesswiper, res);
    }
    //获取女鞋包包热销
    async loadWomenShoesHotsData() {
      let res = await getWomenShoesHotsData();
      this.renderHots(this.womenshoeshots, res);
    }

    //获取男装男鞋数据列表
    async loadMaleShoesData() {
      let res = await getMaleShoesData();
      this.renderMySwiperSix(this.maleshoesswiper, res);
    }
    //获取男装男鞋热销
    async loadMaleShoesHotsData() {
      let res = await getMaleShoesHotsData();
      this.renderHots(this.maleshoeshots, res);
    }

    //获取内衣数据列表
    async loadUnderwearData() {
      let res = await getUnderwearData();
      this.renderMySwiperSix(this.underwearswiper, res);
    }
    //获取内衣热销
    async loadUnderwearHotsData() {
      let res = await getUnderwearHotsData();
      this.renderHots(this.underwearhots, res);
    }
    //内衣左侧图片切换
    toggleImg() {
      let imglist = ['https://s10.mogucdn.com/mlcdn/c45406/200902_412fe9ehh20f6ic8le0i4i1h687cd_690x1665.png_750x9999.v1c7E.81.webp', 'https://s10.mogucdn.com/mlcdn/c45406/180516_2838ae209bh533h353ie13bh24blc_690x1665.jpg_750x9999.v1c7E.81.webp'];
      this.underwearimgTimer = setInterval(() => {
        this.underwearleftimg.children('img').prop('src', this.underwearleftimg.children('img').prop('src') === imglist[0] ? imglist[1] : imglist[0]);
      }, 6000);
    }

    //获取家纺家饰数据列表
    async loadHomeDecorationData() {
      let res = await gethomedecorationData();
      this.renderMySwiperSix(this.homedecorationswiper, res);
      // this.initCSildesSwiper();
    }
    //获取家纺家饰热销
    async loadHomeDecorationHotsData() {
      let res = await gethomedecorationHotsData();
      this.renderHots(this.homedecorationhots, res);
    }

    //获取母婴童装数据列表
    async loadKidwearData() {
      let res = await getkidwearData();
      this.renderMySwiperSix(this.kidwearswiper, res);
      // this.initCSildesSwiper();
    }
    //获取母婴童装热销
    async loadKidwearHotsData() {
      let res = await getkidwearHotsData();
      this.renderHots(this.kidwearhots, res);
    }

    //获取猜你喜欢数据列表
    async loadGuessYouLikeData() {
      let res = await getGuessYouLike();
      this.renderGuessYouLike(res);
    }

    //倒计时功能
    countDown() {
      this.countDownTimer = setInterval(() => {
        let now = +new Date();
        let target = new Date();
        target.setDate(target.getDate() + 1);
        target.setHours(0);
        target.setMinutes(0);
        target.setSeconds(0);
        target = target.getTime();
        let time = (target - now) / 1000;
        let seconds = parseInt(time % 60);
        let minutes = parseInt(time / 60 % 60);
        let hours = parseInt(time / 60 / 60 % 24);
        seconds = seconds < 10 ? '0' + seconds : seconds;
        minutes = minutes < 10 ? '0' + minutes : minutes;
        hours = hours < 10 ? '0' + hours : hours;
        this.rubhours.html(hours);
        this.rubminutes.html(minutes);
        this.rubseconds.html(seconds);
      }, 1000);
    }

    //渲染分组轮播图数据列表
    renderMySwiper(wrap, res) {
      $.each(res.data, (index, item) => {
        let swiperSilde = $(`<div class="swiper-slide"></div>`);
        swiperSilde.html(`
          <img src="${item.img_path}">
          <div class="goods-info">
            <p class="title">${item.title}</p>
            <p class="price">￥${parseInt(item.price.trim().slice(1)).toFixed(2)}</p>
          </div>
        `);
        wrap.append(swiperSilde);
      });
    }

    //渲染6张一次滚动轮播图
    renderMySwiperSix(wrap, res) {
      let str = ``;
      res.data.map((item, index) => {
        if(index % 6 === 0) {
          str += `<div class="swiper-slide"><ul>`;
        }
        str += `
        <li>
          <img src="${item.img_path}" alt="">
          <div class="goods-info">
            <p class="title">
              ${item.title}
            </p>
            <p class="price">
              ￥${parseInt(item.price.trim().slice(1)).toFixed(2)}
            </p>
          </div>
        </li>
        `;
        if((index % 6 === 5) || (index === res.data.length - 1)) {
          str += `</ul></div>`;
        }
      });
      wrap.html(str);
    }
    //渲染热销
    renderHots(wrap, res) {
      $.each(res.data, (index, item) => {
        let li = $('<li></li>');
        li.html(`
          <img src="${item.img_path}">
          <div class="hot-goods-info">
            <p class="hot-goods-title">${item.title}</p>
            <p class="hot-goods-price">${item.price}</p>
          </div>
        `);
        wrap.append(li);
      });
    }
    //渲染猜你喜欢列表
    renderGuessYouLike(res) {
      this.guessyoulike.html(`
        ${res.data.map(item => {
          return `
          <li ${item.tradeItemId ? `data-tradeItemId=${item.tradeItemId}` : ''}>
            <div class="img">
              <img data-src="${item.img_path}" alt="">
            </div>
            <p class='title'>
              ${item.title}
            </p>
            <div class='goods-info clearfix'>
              <div class='price fl'>${item.price}</div>
              <div class='store fr'>
                <i></i>
                <span class='store-count'>${item.store}</span>
              </div>
            </div>
          </li>
          `;
        }).join('')}
      `);
      new LazyLoad('.guess-you-like img');
    }
  }


  //楼梯层
  class Floor {
    constructor() {
      //获取粘滞导航的高度
      this.sticky_header_height = $('#sticky-header').outerHeight();
      //电梯导航互斥锁
      this.flag = true;
      //获取楼层
      this.floors = $('.floor');
      //获取电梯按钮
      this.floors_btns = $('.floor-btns');
      //获取电梯返回顶部
      this.floor_backtop = $('.floor-btns #floorbacktop');
      //获取所有的电梯按钮
      this.btns = $('.floor-btns ul li');
      //定义显示电梯按钮高度
      this.show_top = this.floors.eq(1).offset().top;
      //定义显示返回顶部高度
      this.show_backtop_top = this.floors.eq(3).offset().top;
      //获取页脚到也免得顶部高度
      this.footer = $('footer');
      this.floorsTop = 0;
      //控制变量
      this.flag = true;
      this.bindEvent();
      $(document).trigger('scroll');
    }
    //绑定事件
    bindEvent() {
      //保存实例对象
      let _this = this;
      $(document).on('scroll', () => {
        this.showFloorsBtns();
        this.showOnly();
      });
      this.floor_backtop.on('click', () => {
        this.floorbackTop();
      });
      this.btns.on('click', function() {
        _this.flag = false;
        let top = _this.floors.eq($(this).index()).offset().top;
        top -= _this.sticky_header_height;
        $(this).addClass('active').siblings().removeClass('active');
        $('html,body').stop(true).animate({
          scrollTop: top
        }, () => {
          _this.flag = true;
        });
      });
    }

    //控制按钮显示隐藏
    showFloorsBtns() {
      //获取第二层女装楼层到页面顶端的高度作为显示电梯按钮的临界值
      if(this.show_top <= $(document).scrollTop() + $(window).height()) {
        this.floors_btns.stop(true).fadeIn();
      }else {
        this.floors_btns.stop(true).css('display', 'none');
      }
      
      if(this.show_backtop_top <= $(document).scrollTop() + $(window).height()) {
        this.floor_backtop.css('height', 30);
      }else {
        this.floor_backtop.css('height', 0);
      }

      if(this.floors_btns.offset().top + this.floors_btns.outerHeight() >= this.footer.offset().top) {
        let _top = this.footer.offset().top - this.floors_btns.outerHeight();
        this.floors_btns.css({
          position: 'absolute',
          transform: 'translateY(0)',
          top: _top
        });
      }else if(this.floors_btns.offset().top - $(document).scrollTop() >= (innerHeight - this.floors_btns.outerHeight()) / 2) {
        this.floors_btns.css({
          position: 'fixed',
          transform: 'translateY(-50%)',
          top: '50%'
        });
      }
    }
    //返回顶部功能
    floorbackTop() {
      $('html,body').stop(true).animate({
        scrollTop: 0
      }, 500);
    }
    //滚动对应显示
    showOnly() {
      if(this.flag) {
        this.floors.each((index, floor) => {
          if($(document).scrollTop() >= $(floor).offset().top - this.sticky_header_height - 1) {
            this.btns.eq(index).addClass('active').siblings().removeClass('active');
          }
        });
      } 
    }
  }

  new Index();
  new Floor();
});

